package com.auxgroup.smarthome.baidu;

import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.GlobalParamsConstant;
import com.auxgroup.smarthome.regex.RegexUtils;
import com.auxgroup.smarthome.utils.HttpClientUtil;
import org.apache.commons.lang3.tuple.Triple;

/**
 * Created by kevinchen on 2017/6/11.
 * 暂时提供普通IP定位api,只能够获得指定IP所处大致位置，结果字段中所返回的经纬度坐标一般为城市中心点坐标，请开发者注意使用
 * 详情请参加如下链接：http://lbsyun.baidu.com/index.php?title=webapi/ip-api
 *
 * rHg4NzdG8RYdjtLUpGa3PVhpFxR8FGOP
 */
public class BaiduUtils {

    public static final String LOCATION_IP = "http://api.map.baidu.com/location/ip";

    /**
     * 暂时只支持国内的ip,返回中文的（未使用汉语拼音）国内省份与城市
     * @param ip
     * @return
     */
    public static Triple<String,String,String> getLocationByIp(String ip){
        // 正在表达式 校验ip合法性
        boolean flag = RegexUtils.checkIpAddress(ip);
        if (!flag)
            return null;
        else {
            String result = HttpClientUtil.httpRequest(LOCATION_IP+"?ip=" + ip + "&ak=" + GlobalParamsConstant.BAIDU_AK, null, "", HttpClientUtil.MethodType.METHOD_GET);
            JSONObject json = JSONObject.parseObject(result);
            String province = json.getJSONObject("content").getJSONObject("address_detail").getString("province");
            String city = json.getJSONObject("content").getJSONObject("address_detail").getString("city");
            Triple<String, String, String> triple = Triple.of("中国", province, city);
            return triple;
        }
    }

}
